package com.winning.sx.microframework.task;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.sx.microframework.common.util.Constains;
import com.winning.sx.microframework.plugins.wx.WxUtil;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.GenericApiService;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class MessageTask {
    @Autowired
    private EasyService easyService;
    @Autowired
    private GenericApiService genericApiService;
    private static Logger log = Logger.getLogger(MessageTask.class);



    //定时任务   微信
//    @Scheduled(cron = "0/10 * * * * ? ")
//    @Scheduled(fixedDelay = 5000)
    public void doWxTask() {
        Map taskLog = new HashMap<>();
        int success = 0;
        taskLog.put("name", "定时任务-微信");
        taskLog.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        try {

            Map param = new HashMap<>();
            param.put("type", Constains.MESSAGE_WX);
            param.put("state", Constains.MESSAGE_NEW);
            List all = easyService.queryList("BASE_Message", param).getDataRows();
            for (int i = 0; i < all.size(); i++) {
                Map map = (Map) all.get(i);
                Map messageUpdate = new HashMap();
                messageUpdate.put("id", map.get("id").toString());

                //此处应向短信发送消息
                Map openIdParam = new HashMap();
                openIdParam.put("staffId", map.get("staffId").toString());
                openIdParam.put("state", Constains.STATE_NORMAL);
                try {
                    Map openId=null;
                    if(map.get("openId")!=null){
                        openId=new HashMap();
                        openId.put("openId",map.get("openId").toString());
                    }else{
                        openId= easyService.queryEntity("PM_StaffWeChat", openIdParam);
                    }
                    if (openId != null) {
                        ObjectMapper objectMapper = new ObjectMapper();
                        Map messageWx = objectMapper.readValue(map.get("sendContext").toString(), Map.class);
                        messageWx.put("template",map.get("template").toString());
                        String errMsg = sendTemplateInfo(messageWx,openId.get("openId").toString());
                        Map updateMap = new HashMap();
                        if ("ok".equals(errMsg)) {
                            messageUpdate.put("state", Constains.MESSAGE_SUCCESS);
                            success++;
                        }else{
                            int failCount = 0;
                            if (map.get("failCount") != null && !"".equals(map.get("failCount"))) {
                                failCount = Integer.valueOf(map.get("failCount").toString());
                            }
                            failCount++;
                            messageUpdate.put("failCount", failCount+"");
                            if (failCount > 5) {
                                messageUpdate.put("state", Constains.MESSAGE_FALSE);
                            }
                        }
                    }else{
                        messageUpdate.put("state", Constains.MESSAGE_FALSE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    messageUpdate.put("state", Constains.MESSAGE_FALSE);
                    continue;
                }
                easyService.update("BASE_Message", "id", messageUpdate);
            }

        } catch (Exception e) {
            String msg = e.getMessage();
            if (msg.length() > 50)
                msg = msg.substring(0, 49) + "……";
            taskLog.put("errorMsg", msg);
        } finally {
            try {
                taskLog.put("count", success+"");
                taskLog.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                //防止日志过多，保留最近的360条
                easyService.deleteDeep("delete from SYS_PlanLog where id<(" +
                        " select max(id)-360 from SYS_PlanLog" +
                        ")",new HashMap<>());
                easyService.insert("SYS_PlanLog", taskLog);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    }
    private String sendTemplateInfo(Map message,String openId) throws IOException {
        List sendInfoList = new ArrayList();
        sendInfoList.add(openId);
        sendInfoList.add(getTemplateId(message.get("template").toString()));
        sendInfoList.add(message.get("url"));
        sendInfoList.add(message.get("first"));
        String content = message.get("content").toString();
        String[] contentArr = content.split("@#@");
        for (int i = 0; i < contentArr.length; ++i) {
            sendInfoList.add(contentArr[i]);
        }
        sendInfoList.add(message.get("remark"));
        String sendTemplateInfo= WxUtil.sendTemplateInfo(sendInfoList);
        JSONObject jsonObject = JSONObject.fromObject(sendTemplateInfo);
		/*if ("ok".equals(jsonObject.getString("errmsg"))) {
			return 1;
		}
		return 0;*/
        return jsonObject.getString("errmsg");
    }

    private String getTemplateId(String template){
        switch (template){
            case Constains.MESSAGE_TEMPLATE_1:
                return "qF4z-_cFauMr0g2sNzZZVcj3S-fV-WTB8f29CpJG8as";//新申请通知受理人
            case Constains.MESSAGE_TEMPLATE_2:
                return "DoLkC6QJQajTeMTGCySu5gy0DR-c5cnF2LRVR6g_sc0";//接单状态通知申请人
            case Constains.MESSAGE_TEMPLATE_3:
                return "gXyvLUZXLUv_lX3DkgV1IQrAIZEBwcrZJ6ggDBEM_0I";//派单通知维修工
            case Constains.MESSAGE_TEMPLATE_4:
                return "86uWFUuAmyVipkvS7_fVQAE3chzEQfywsGY6A-0PsEc";//维修结果
            case Constains.MESSAGE_TEMPLATE_5:
                return "uWNpySJrFQaktfgSMcgSvYbgN1qv2apUx_62DAZgU2k";//接单结果

            default:
                return "";
        }
    }
}
